import React, {
  forwardRef,
  useEffect,
  useImperativeHandle,
  useMemo,
  useState,
} from "react";
import { Icon as Icon2 } from "../../../components/Icon";
import Icon from "react-native-vector-icons/Ionicons";
import {
  Text,
  View,
  TouchableOpacity,
  Alert,
  Image,
  TouchableWithoutFeedback,
  Platform,
} from "react-native";
import { Calendar, LocaleConfig } from "react-native-calendars";
import /*RFValue*/ "react-native-responsive-fontsize";
import { useTheme } from "styled-components";
import moment from "moment";
import * as S from "../styles";
import { useTasks } from "../../../hooks/useTasks";

const overviewIcon = require("../../../assets/images/icon_overview.png");
const chartIcon = require("../../../assets/images/icon_chart.png");

LocaleConfig.locales["zh"] = {
  monthNames: [
    "一月",
    "二月",
    "三月",
    "四月",
    "五月",
    "六月",
    "七月",
    "八月",
    "九月",
    "十月",
    "十一月",
    "十二月",
  ],
  monthNamesShort: [
    "一月",
    "二月",
    "三月",
    "四月",
    "五月",
    "六月",
    "七月",
    "八月",
    "九月",
    "十月",
    "十一月",
    "十二月",
  ],
  dayNames: [
    "星期日",
    "星期一",
    "星期二",
    "星期三",
    "星期四",
    "星期五",
    "星期六",
  ],
  dayNamesShort: ["周日", "周一", "周二", "周三", "周四", "周五", "周六"],
  today: "今天",
};

LocaleConfig.defaultLocale = "zh";

moment.updateLocale("zh-cn", {
  months:
    "一月_二月_三月_四月_五月_六月_七月_八月_九月_十月_十一月_十二月".split(
      "_"
    ),
  monthsShort: "1月_2月_3月_4月_5月_6月_7月_8月_9月_10月_11月_12月".split("_"),
  weekdays: "周日_周一_周二_周三_周四_周五_周六".split("_"),
  weekdaysShort: "周日_周一_周二_周三_周四_周五_周六".split("_"),
  weekdaysMin: "日_一_二_三_四_五_六".split("_"),
});

moment.locale("zh-cn");

const Header = forwardRef((props, ref) => {
  const theme = useTheme();
  const [isModalSelectDateOpen, setIsModalSelectDateOpen] = useState(false);
  const [selectedDate, setselectedDate] = useState(
    moment().format("YYYY-MM-DD")
  );

  const [selectedRange, setSelectedRange] = useState({
    startDate: null,
    endDate: null,
    displayedDate: {},
  });

  useImperativeHandle(ref, () => ({
    toggleModal: () => {
      toggleModal();
    },
  }));

  const onDaySelect = (day) => {
    const { dateString } = day;
    let { startDate, endDate, displayedDate } = selectedRange;

    if (startDate && !endDate && dateString >= startDate) {
      // 如果已经选择了开始日期，并且当前选择的日期大于等于开始日期，则设置结束日期
      endDate = dateString;
      displayedDate = getMarkedDates(startDate, endDate);
      props?.selectedRangeCallback &&
        props?.selectedRangeCallback([startDate, endDate]);
      toggleModal();
    } else {
      // 否则，设置开始日期并重置结束日期
      startDate = dateString;
      endDate = null;
      displayedDate = {
        [dateString]: {
          startingDay: true,
          endingDay: true,
          color: "#50cebb",
          textColor: "white",
        },
      };
    }
    setSelectedRange({ startDate, endDate, displayedDate });
  };

  const getMarkedDates = (start, end) => {
    const markedDates = {};
    let currentDate = start;

    while (currentDate <= end) {
      if (currentDate === start) {
        markedDates[currentDate] = {
          startingDay: true,
          color: "#50cebb",
          textColor: "white",
        };
      } else if (currentDate === end) {
        markedDates[currentDate] = {
          endingDay: true,
          color: "#50cebb",
          textColor: "white",
        };
      } else {
        markedDates[currentDate] = { color: "#70d7c7", textColor: "white" };
      }
      currentDate = incrementDate(currentDate);
    }

    return markedDates;
  };

  const incrementDate = (date) => {
    const dt = new Date(date);
    dt.setDate(dt.getDate() + 1);
    return dt.toISOString().split("T")[0];
  };

  useEffect(() => {}, []);

  const formattedDateSelected = useMemo(() => {
    if (selectedDate) {
      const [year, month, day] = selectedDate.split("-");
      return `${year}.${month}.${day}`;
    }

    return "";
  }, [selectedDate]);

  function toggleModal() {
    setIsModalSelectDateOpen(!isModalSelectDateOpen);
  }

  const { loadTasks, updateActiveDate, updateStartDate } = useTasks();

  let rightIcon = (
    <Icon2 name="edit" size={/*RFValue*/ 24} color={"rgba(65, 79, 102, 1)"} />
  );
  let bgColor = { backgroundColor: "rgba(245,245,245,1)" };
  if (props?.from === "calculate") {
    rightIcon = (
      <Image
        source={overviewIcon}
        style={{ width: /*RFValue*/ 24, height: /*RFValue*/ 24 }}
      />
    );
    bgColor = { backgroundColor: "#fff" };
  } else if (props?.from === "statistics") {
    rightIcon = (
      <Image
        source={chartIcon}
        style={{ width: /*RFValue*/ 24, height: /*RFValue*/ 24 }}
      />
    );
    bgColor = { backgroundColor: "#fff" };
  }

  return (
    <View
      style={{
        height: /*RFValue*/ 44,
        alignItems: "center",
        flexDirection: "row",
        marginHorizontal: /*RFValue*/ 16,
        marginVertical: /*RFValue*/ 9,
      }}
    >
      <S.StyledModal
        visible={isModalSelectDateOpen}
        animationType="fade"
        onRequestClose={toggleModal}
        presentationStyle="overFullScreen"
        transparent
      >
        <TouchableWithoutFeedback onPress={toggleModal}>
          <S.ModalOverlay>
            <S.ModalContent>
              <S.CalendarWrapper>
                <Calendar
                  markingType={props?.selectPeriod && "period"}
                  style={{
                    alignItems: "center",
                    justifyContent: "center",
                  }}
                  showSixWeeks={true}
                  initialDate={selectedDate}
                  theme={{
                    "stylesheet.calendar.main": {
                      dayContainer: {
                        width: /*RFValue*/ 44,
                        height: /*RFValue*/ 44,
                        fontSize: /*RFValue*/ 24,
                        alignItems: "center",
                        justifyContent: "center",
                        marginHorizontal: /*RFValue*/ 2,
                      },
                    },
                    "stylesheet.calendar.header": {
                      monthText: {
                        fontSize: /*RFValue*/ 20,
                        fontFamily: "HarmonyOS_Sans_SC_Regular",
                        color: "rgba(0, 0, 0, 1)",
                      },
                      arrow: {
                        height: /*RFValue*/ 15,
                        width: 15,
                      },
                      arrowImage: {
                        tintColor: "rgba(67, 113, 177, 1)",
                        height: /*RFValue*/ 15,
                        width: 10,
                      },
                      week: {
                        width: Platform.OS === "android" ? "100%" : "98%",
                        paddingLeft: /*RFValue*/ 20,
                        marginTop: /*RFValue*/ 7,
                        marginBottom: /*RFValue*/ 13,
                        flexDirection: "row",
                        justifyContent: "space-between",
                      },
                      dayHeader: {
                        marginTop: 2,
                        marginBottom: 7,
                        textAlign: "center",
                        fontSize: /*RFValue*/ 13,
                        fontFamily: "HarmonyOS_Sans_SC_Regular",
                        fontWeight: 400,
                        color: "rgba(60, 60, 67, 0.3)",
                      },
                    },
                    "stylesheet.day.basic": {
                      base: {
                        width: /*RFValue*/ 44,
                        height: /*RFValue*/ 44,
                        borderRadius: /*RFValue*/ 22,
                        alignItems: "center",
                        justifyContent: "center",
                        alignSelf: "center",
                        textAlign: "center",
                        alignContent: "center",
                      },
                      text: {
                        fontSize: /*RFValue*/ 19,
                        fontFamily: "HarmonyOS_Sans_SC_Regular",
                        fontWeight: 400,
                        color: "rgba(0, 0, 0, 1)",
                      },
                      selected: {
                        backgroundColor: "rgba(78, 112, 172, 0.16)",
                        borderRadius: /*RFValue*/ 22,
                        width: /*RFValue*/ 44,
                        height: /*RFValue*/ 44,
                        alignItems: "center",
                        justifyContent: "center",
                      },
                      selectedText: {
                        color: "rgba(0, 0, 0, 1)",
                        fontSize: /*RFValue*/ 19,
                        fontFamily: "HarmonyOS_Sans_SC_Regular",
                        fontWeight: 400,
                      },
                    },
                    // "stylesheet."
                    calendarBackground: theme.colors["background-variant"],
                    selectedDayTextColor: "rgba(0, 0, 0, 1)",
                    selectedDayBackgroundColor: "rgba(78, 112, 172, 0.16)",
                  }}
                  focusable
                  markedDates={
                    props?.selectPeriod
                      ? selectedRange.displayedDate
                      : { [selectedDate]: { selected: true } }
                  }
                  maxDate={moment().format("YYYY-MM-DD")}
                  onDayPress={(date) => {
                    if (props?.selectPeriod) {
                      onDaySelect(date);
                    } else {
                      props.selectDateCallback &&
                        props.selectDateCallback(date.dateString);
                      setselectedDate(date.dateString);
                      toggleModal();
                      if (
                        props?.from === "calculate" ||
                        props?.from === "statistics"
                      ) {
                        return;
                      }
                      loadTasks({
                        startDate: moment(date.dateString)
                          .subtract(6, "days")
                          .format("YYYY-MM-DD"),
                        endDate: moment(date.dateString).format("YYYY-MM-DD"),
                      });
                      updateActiveDate(date.dateString);
                      updateStartDate(date.dateString);
                      props?.listRef?.current?.scrollToTop();
                    }
                  }}
                />
              </S.CalendarWrapper>
            </S.ModalContent>
          </S.ModalOverlay>
        </TouchableWithoutFeedback>
      </S.StyledModal>
      <View style={{ flex: 3, flexDirection: "row" }}>
        <TouchableOpacity
          style={{ flexDirection: "row", alignItems: "center" }}
          onPress={() => {
            props.toggleModalCallback && props.toggleModalCallback();
            setTimeout(() => {
              toggleModal();
            }, 10);
          }}
        >
          <Text
            style={{
              fontSize: /*RFValue*/ 18,
              fontFamily: "HarmonyOS_Sans_SC_Bold",
              fontWeight: 700,
              color: "rgba(0, 0, 0, 0.9)",
            }}
          >
            {formattedDateSelected} {moment(selectedDate).format("ddd")}
          </Text>
          <Icon
            style={{ marginLeft: 10 }}
            name="caret-down"
            size={12}
            color="rgba(0, 0, 0, 0.9)"
          />
        </TouchableOpacity>
      </View>
      <View style={{ flex: 1, alignItems: "flex-end" }}>
        <TouchableOpacity
          onPress={() => {
            props.iconClick && props.iconClick();
          }}
          style={{
            alignItems: "center",
            justifyContent: "center",
            width: /*RFValue*/ 40,
            height: /*RFValue*/ 40,
            borderRadius: 146,
            ...bgColor,
          }}
        >
          {rightIcon}
        </TouchableOpacity>
      </View>
    </View>
  );
});
export default Header;
